const jwt = require('jsonwebtoken')
const Rsa = require('./Rsa')
class Jwt {
    constructor() {

    }
    /**
     * 加密token
     * data :{id:'59a62b0b790c1a5ea72b1ea3', username: 'Mankong'}
     * @param {any} data 
     * @returns 
     * @memberof Jwt
     */
    async sign(data) {
        let token  = await jwt.sign({
            exp: data.exp ? data.exp: (Date.now() + 1000 * 86400 * 1) / 1000,
            data: data.data
        }, Rsa.private_key, { algorithm: 'RS256' })
        return token
    }
    /**
     * 验证token
     * 
     * @param {any} token 
     * @returns 
     * @memberof Jwt
     */
    async verify(token) {
        try {
            let data = await jwt.verify(token, Rsa.public_key, { algorithm: 'RS256' })
            return data
        } catch (error) {
            console.trace(error)
            return false
        }
    }

    /**
     * 解密token
     * 
     * @param {any} token 
     * @returns 
     * @memberof Jwt
     */
    async decode(token) {
        try {
            let data = jwt.decode(token, {complete: true})
            return data
        } catch (error) {
            return false
        }
    }

}

module.exports = new Jwt()